package com.celerity.server.connection.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import com.celeritymq.server.connection.ConnectionHolder;
/**
 * 
 * @author max
 * 以此类为各种连接的中心类
 */
public class ConnectionHolderImpl implements ConnectionHolder{
	private Selector selector;
	private ServerSocketChannel serverSocketChannel;
	private ServerSocket serverSocket;
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() throws IOException {
		selector=Selector.open();
		serverSocketChannel=ServerSocketChannel.open();
		serverSocket=serverSocketChannel.socket();
		serverSocket.setReuseAddress(true);
		serverSocketChannel.configureBlocking(false);
		serverSocket.bind(new InetSocketAddress(8888));
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
	}
	
	private void service() throws IOException{
		while(selector.select()>0){
			Set<SelectionKey> readyKeys=selector.selectedKeys();
			Iterator<SelectionKey> it=readyKeys.iterator();
			while(it.hasNext()){
				SelectionKey key=it.next();
				it.remove();
//				int readyOps=key.readyOps();
				if(key.isAcceptable()){
					ServerSocketChannel serverSocketChannel=(ServerSocketChannel) key.channel();
					SocketChannel socketChannel=serverSocketChannel.accept();
				}
				
				
			}
		}
	}

	@Override
	public void removeConnection() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void holdConnection() {
		// TODO Auto-generated method stub
		
	}

}
